import { defineStore } from 'pinia'
import {
  type setType,
  store,
  getConfig,
  storageLocal,
  responsiveStorageNameSpace
} from '../util'

export const useSettingStore = defineStore('easy-setting', {
  state: (): setType => ({
    title: getConfig().Title,
    fixedHeader: getConfig().FixedHeader,
    hiddenSideBar: getConfig().HiddenSideBar,
    collapseSideBar: false,
    panel: false, // 是否开启设置的弹框面板
    configure:
      storageLocal().getItem<StorageConfigs>(
        `${responsiveStorageNameSpace()}configure`
      ) || (getConfig() as StorageConfigs)
  }),
  getters: {
    getTitle(state) {
      return state.title
    },
    getFixedHeader(state) {
      return state.fixedHeader
    },
    getHiddenSideBar(state) {
      return state.hiddenSideBar
    },
    getMainHeight(state) {
      return `calc(100% - 48px ${state.configure.hideTabs ? '' : '- 40px'})`
    }
  },
  actions: {
    CHANGE_SETTING([key, value]) {
      if (Reflect.has(this, key)) {
        this[key] = value
        this.SET_CONFIGURE([[key, value]])
      }
    },
    SET_CONFIGURE(...args: any[]): void {
      const storageKey = `${responsiveStorageNameSpace()}configure`

      if (args.length === 1 && Array.isArray(args[0])) {
        // 处理数组情况
        const entries = args[0]
        entries.forEach(([key, val]) => {
          this.configure[key] = val
        })
      } else if (args.length === 2) {
        // 处理单个 key, val 情况
        const [key, val] = args
        this.configure[key] = val
      } else {
        throw new Error('Invalid arguments for SET_CONFIGURE function')
      }

      // 将更新后的布局保存到 localStorage
      storageLocal().setItem(storageKey, this.configure)
    },
    collapseSider() {
      this.collapseSideBar = !this.collapseSideBar
    },
    openPanel(val: boolean) {
      this.panel = val
    }
  }
})

export function useSettingStoreHook() {
  return useSettingStore(store)
}
